%write 1 minute magnetic data 1995:2006 to a 
% netcdf file
%expects NaN to fill in no data points

function[Err] = write_mag_netcdf(x_data,y_data,z_data,nc_fname)

a = sum(daysinyear([1995:2006]))*24*60;
start_date = datenum(1995,1,1);

S1 = dir(nc_fname);

if isempty(S1),
ncid = netcdf.create(nc_fname,'NC_NOCLOBBER');
data_time_axis_dim = netcdf.defDim(ncid,'data_time_axis_dim',a);
X_ID = netcdf.defVar(ncid,'X_secular_removed','int', data_time_axis_dim);
Y_ID = netcdf.defVar(ncid,'Y_secular_removed','int', data_time_axis_dim);
Z_ID = netcdf.defVar(ncid,'Z_secular_removed','int', data_time_axis_dim);
netcdf.putAtt(ncid,X_ID,'_FillValue',int32(999999));
netcdf.putAtt(ncid,Y_ID,'_FillValue',int32(999999));
netcdf.putAtt(ncid,Z_ID,'_FillValue',int32(999999));
netcdf.endDef(ncid);
else
ncid = netcdf.open(nc_fname,'NC_WRITE');
X_ID = netcdf.inqVarID(ncid,'X_secular_removed');
Y_ID = netcdf.inqVarID(ncid,'Y_secular_removed');
Z_ID = netcdf.inqVarID(ncid,'Z_secular_removed');
end;


y_data(isnan(y_data)) = 99999.9;    %no data (this will get converted to 999999 by int32(99999.9*10)
where_to_store = 0;%assumes all incoming data starts at start_date
length_of_record = a;
netcdf.putVar(ncid, Y_ID, where_to_store, length_of_record,  int32 (y_data .* 10) );

x_data(isnan(x_data)) = 99999.9;    %no data (this will get converted to 999999 by int32(99999.9*10)
where_to_store = 0;
length_of_record = a;
netcdf.putVar(ncid, X_ID, where_to_store, length_of_record,  int32 (x_data .* 10) );

z_data(isnan(z_data)) = 99999.9;    %no data (this will get converted to 999999 by int32(99999.9*10)
where_to_store = 0;
length_of_record = a;
netcdf.putVar(ncid, Z_ID, where_to_store, length_of_record,  int32 (z_data .* 10) );

netcdf.close(ncid);
Err=1;

